package cn.opencodes.framework.core.datasources;

import java.lang.reflect.Method;

import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;

/**
 * 多数据源，切面处理类
 * @author HJ
 */
@Aspect
@Order(1)
public class DataSourceAspect{
    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Pointcut("@annotation(cn.opencodes.framework.core.datasources.DataSource)")
    public void dataSourcePointCut() {}

    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        try {
        	MethodSignature signature = (MethodSignature) point.getSignature();
            Method method = point.getTarget().getClass().getMethod(
            		signature.getName(), signature.getParameterTypes());
            //通过方法获得注解
            DataSource ds = method.getAnnotation(DataSource.class);
        	if(StringUtils.isNotBlank(ds.name())){
        		DynamicDataSource.setDataSource(ds.name());
        		logger.debug("set datasource is " + ds.name());
        	}
            return point.proceed();
        } finally {
            DynamicDataSource.clearDataSource();
            logger.debug("clean datasource");
        }
    }

}
